package com.access.config;


import cn.hutool.core.util.StrUtil;
import com.access.trace.Constant;
import com.access.utils.HttpUtil;
import com.access.validator.url.UrlValidator;
import com.access.validator.user.UserInformation;
import com.access.validator.user.UserValidator;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lei
 * @create 2024-08-22
 * @desc 继续向下游传递traceId以及当前操作用户信息
 **/
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        String traceId = MDC.get(Constant.TRACE_ID);
        if (StrUtil.isNotBlank(traceId)) {
            template.header(Constant.TRACE_ID, traceId);
        }
        UserInformation userInfo = MSInterceptor.USER_INFORMATION.get();
        if (userInfo != null) {
            template.header(UserValidator.USER_INFORMATION, HttpUtil.writeUserInfoToHeaderString(userInfo));
            return;
        }
        HttpServletRequest request = MSInterceptor.REQUEST_INFORMATION.get();
        if (null != request) {
            String jwt = request.getHeader(UrlValidator.GATEWAY_AUTHORIZATION);
            if (null != jwt && !jwt.isEmpty()) {
                template.header(UrlValidator.GATEWAY_AUTHORIZATION, jwt);
            }
        }
    }

}
